package com.szyjjk.imageCrawler;

import com.szyjjk.entity.SysImageCrawler;
import com.szyjjk.service.SysImageCrawlerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Observable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @program: hyybypt
 * @description: 爬虫下载入口
 * @author: yangyue
 * @create: 2019-08-05 14:08
 */
@Component
public class CrawlerMain {
    @Autowired
    private SysImageCrawlerService sysImageCrawlerService;

    public static CrawlerMain crawlerMain;

    @PostConstruct
    public void init() {
        crawlerMain = this;
        this.sysImageCrawlerService = crawlerMain.sysImageCrawlerService;
    }
  
    private static final long PERIOD_DAY  = 24 * 60 * 60 * 1000;  //这是一天

    /**
     * @Author yangyue
     * @Description //TODO 开始处理循环数据
     * @Date 14:42 2019/11/26
     * @Param []
     * @return void
     **/
    public static void ModQury() {
        //第一步查询所有爬虫表
        List<SysImageCrawler> allCralerList=crawlerMain.sysImageCrawlerService.findCrewlerAll();
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();     //单个线程池
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(4); //定时任务池
        for (SysImageCrawler crawler : allCralerList) {

            //开始挨个处理
            //首先处理需要一直执行的葵花八Himiwari 数据
            //如果是Himiwari参数的话 就执行单个一直循环的参数
            if(crawler.getBeginTime()==null){
                //如果开始时间是空，则说明一直循环
                cachedThreadPool.execute(new crawlerThread(crawler) );
            }else{
                //如果有时间说明是定时任务 特质
                 //Aviso  绿潮 海冰  H2B
                //首先获取今天的开始时间
                Date begtime=CrawlerTool.getTimeTaday(crawler.getBeginTime(),0);
                //当前时间
                Date newDate=new Date();
                //差距多少毫秒
                long  timeB=newDate.getTime()-begtime.getTime();
                if(timeB>=0){
                    //如果时间已经过去了，那么先立即执行，然后去定时距离下次执行时间为   （明天的开始时间-现在时间） 循环24小时执行
                    //立即执行
                    cachedThreadPool.execute(new crawlerThread(crawler) );
                    // 计算下次开始时间
                    Date yesterday=CrawlerTool.getTimeTaday(crawler.getBeginTime(),1);      //+1天
                    //距离下次执行事假为
                    long yesDate=yesterday.getTime()-newDate.getTime();
                    //开启定时任务     执行任务体   距离时间   循环时间
                    executor.scheduleAtFixedRate(new crawlerThread(crawler), yesDate, PERIOD_DAY, TimeUnit.MILLISECONDS);

                }else{
                    //如果是大于的加，那么久隔  今天的开始时间-现在时间  循环24小时执行
                    executor.scheduleAtFixedRate(new crawlerThread(crawler), timeB, PERIOD_DAY, TimeUnit.MILLISECONDS);
                }
            }
        }
    }


    /**
     * @Author yangyue
     * @Description //TODO 数据库查询数据  根据ID 查询
     * @Date 14:43 2019/11/26
     * @Param []
     * @return void
     **/
    public static SysImageCrawler getCrawler(String id){
       return  crawlerMain.sysImageCrawlerService.findByIdCrawler(id);
    }

}

/**
 * @Author yangyue
 * @Description //TODO 线程
 * @Date 15:58 2019/8/5
 * @Param
 * @return
 **/
class crawlerThread  extends Observable implements Runnable{

    private SysImageCrawler sysImageCrawler;

    public crawlerThread(SysImageCrawler sysImageCrawler) {
        this.sysImageCrawler = sysImageCrawler;
    }

    public void run() {
        //在这里判断今日任务是否执行
        SysImageCrawler Rcrawler=CrawlerMain.getCrawler(sysImageCrawler.getId());     //再次查询
        if(Rcrawler.getDownloadState()==1){
            //开始任务
            try {
                switch (Rcrawler.getSatellite()){
                    case "Aviso":
                        CrawlerFlow.crawlerAviso(Rcrawler);
                        break;
//                    case "H2B":
//                        CrawlerFlow.beginH2B(Rcrawler);
//                        break;
                    case "MOD021KM,MYD021KM":       //海冰
                        CrawlerFlow.crawlerMOD(Rcrawler);
                        break;
                    case "MOD02QKM,MOD021KM,MYD02QKM,MYD021KM":  //绿潮
                        CrawlerFlow.crawlerMOD(Rcrawler);
                        break;
                    case "Himiwari":
                        CrawlerFlow.crawlerHimiwari(Rcrawler);
                        Thread.sleep(30000);
                        run();      //反复执行
                        break;
                    default:
                        //其他的数据
                        CrawlerFlow.beginElse(Rcrawler);
                        CrawlerTool.systemout(  "------------------------------ 一次任务完成（下次任务"+Rcrawler.getCrawlerInterval()+"分钟之后） ------------------------",Rcrawler.getSatellite());
                        Thread.sleep(Rcrawler.getCrawlerInterval()*1000*60);
                        run();      //反复执行
                        break;
                }
            } catch (Exception e) {
                //如果有问题 过5分钟后再继续
                e.printStackTrace();
                CrawlerTool.systemout(  Rcrawler.getCrawlerRemarks()+"网络问题,5分钟后重启    "+e,Rcrawler.getSatellite());
                try {
                    Thread.sleep(30000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                run();
            }
        }else{
            CrawlerTool.systemout( Rcrawler.getCrawlerRemarks()+"   今日下载关闭",Rcrawler.getSatellite());
        }
    }

}
 

